<template>
	<div class="layout-padding">
		<splitpanes horizontal>
			<pane size="60">
				<div class="layout-padding-auto layout-padding-view">
					<el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
						<el-form-item :label="$t('checkStock.billcode')" prop="billcode">
							<CheckStockHSelect v-model="state.queryForm.billcode" style="width: 200px">
							</CheckStockHSelect>
						</el-form-item>

						<el-form-item :label="$t('checkStock.materialCode')" prop="productLineCode">
							<MaterialSelect v-model="state.queryForm.materialCode" style="width: 200px">
							</MaterialSelect>
						</el-form-item>

						<el-form-item :label="$t('checkStock.barcode')" prop="productLineCode">
							<el-input v-model="state.queryForm.barcode" clearable
								:placeholder="$t('checkStock.barcode')" />
						</el-form-item>

						<el-form-item>
							<el-button type="primary" icon="search" @click="query"> {{ $t('so.query')
								}}</el-button>
							<el-button icon="refresh" @click="resetQuery">{{ $t('so.reset')
								}}</el-button>
							<el-button icon="delete" type="danger" @click="deleteStockDetail">{{ $t('checkStock.delete')
								}}</el-button>
						</el-form-item>
						<hr style="border: 0px;">
						<el-form-item :label="$t('bar.printer')" prop="printer">
							<el-select v-model="PrinterName" placeholder="Select" style="width: 160px">
								<el-option :key="ds.id" :label="ds.value" :value="ds.value"
									v-for="ds in printerOptions"></el-option>
							</el-select>

							<el-button type="info" plain icon="Printer" @click="print">
								{{ $t('checkStock.print') }}
							</el-button>

						</el-form-item>
					</el-form>
					<el-table :data="state.dataList" highlight-current-row v-loading="state.loading" border
						style="width: 100%; height: 100%" :cell-style="tableStyle.cellStyle" stripe show-summary
						:summary-method="getSummaries" :header-cell-style="tableStyle.headerCellStyle"
						@row-click="clickRow" ref="tableRef">
						<el-table-column type="selection" width="40" align="center" />
						<el-table-column type="index" label="#" width="80" />
						<el-table-column prop="billCode" :label="$t('checkStock.billcode')" show-overflow-tooltip
							width="150" />
						<el-table-column prop="sourceType" :label="$t('checkStock.sourceType')" show-overflow-tooltip />
						<el-table-column prop="barcode" :label="$t('checkStock.barcode')" width="180"
							show-overflow-tooltip />
						<el-table-column prop="materialCode" :label="$t('checkStock.materialCode')"
							show-overflow-tooltip width="120" />
						<el-table-column prop="materialName" :label="$t('checkStock.materialName')"
							show-overflow-tooltip width="150" />
						<el-table-column prop="materialSpec" :label="$t('checkStock.materialSpec')"
							show-overflow-tooltip width="200" />
						<el-table-column prop="checkQty" :label="$t('checkStock.checkQty')" show-overflow-tooltip>
							<template #default="scope">
								<el-tag type="success" effect="plain">
									{{ scope.row.checkQty }}
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="creationTime" :label="$t('bar.creationTime')" show-overflow-tooltip
							width="180" />
						<el-table-column prop="ckeckFlag" :label="$t('checkStock.checkFlag')" show-overflow-tooltip>
							<template #default="scope">
								<!--根据不同的状态选择不同的颜色的tag-->
								<el-tag :type="scope.row.ckeckFlag === 'Y' ? 'success' : 'danger'"
									:effect="scope.row.ckeckFlag === 'Y' ? 'dark' : 'light'">
									{{ scope.row.ckeckFlag }}
								</el-tag>
							</template>
						</el-table-column>
					</el-table>

					<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
						v-bind="state.pagination" />
				</div>
			</pane>
			<pane size="40">
				<detail ref="detailsRef" />
			</pane>
		</splitpanes>

	</div>
</template>


<script setup lang="ts">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { GetCheckStockReprintHistory, DeleteCheckStockDetail } from '/@/api/platform/wms/checkStock';
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import detail from "../CheckStockHistory/detail.vue";
import CheckStockHSelect from "/@/components/mes/select/CheckStockHSelect.vue";
import MaterialSelect from "/@/components/mes/select/MaterialSelect.vue";
import { useMessage, useMessageBox } from '/@/hooks/message';
import {  getPrinter,barcodePrint } from '/@/api/platform/wms/sp';
import { ElMessage, TabsPaneContext } from 'element-plus';
const { t } = useI18n();
const tableRef = ref();
const detailsRef = ref()
// 搜索变量
const queryRef = ref();
const PrinterName = ref('');
//打印机列表
const printerOptions = ref();
// 初始化数据
onMounted(() => {
  getPrinter({ code: "printerSetup", text: "" }).then((res) => {
    printerOptions.value = res.data;
  });
});
//表格的配置
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
	},
	pageList: GetCheckStockReprintHistory,
});

const { tableStyle, getDataList, sizeChangeHandle, currentChangeHandle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();

	getDataList(false);
	detailsRef.value.query(state.queryForm.billcode, state.queryForm.materialCode, state.queryForm.barcode);
};

const query = () => {

	getDataList();
	detailsRef.value.query(state.queryForm.billcode, state.queryForm.materialCode, state.queryForm.barcode);
};
const getSummaries = (param) => {
	const { columns, data } = param
	const sums: (string | VNode)[] = []
	columns.forEach((column, index) => {
		if (index === 1) {
			sums[index] = h('div', { style: { textDecoration: 'underline', textAlign: 'center' } }, [
				'Sum',
			])
			return
		}
		if (index != 8) return;
		const values = data.map((item) => Number(item[column.property]))
		if (!values.every((value) => Number.isNaN(value))) {
			sums[index] = h('div', { style: { textAlign: 'center' } }, [
				`${values.reduce((prev, curr) => {
					const value = Number(curr)
					if (!Number.isNaN(value)) {
						return Math.round((prev + curr) * 10000) / 10000
					} else {
						return Math.round(prev * 10000) / 10000
					}
				}, 0)}`,
			])
		}
	})

	return sums
}
const deleteStockDetail = () => {
	var selectedAry = tableRef.value.getSelectionRows();
	if (selectedAry.length == 0) {
		return useMessage().error(t('checkStock.mustselect'))
	}
	for (var i = 0; i < selectedAry.length; i++) {
		if (!(selectedAry[i].checkQty == 0 && selectedAry[i].ckeckFlag == 'Y')) {
			return useMessage().error(selectedAry[i].barcode + ' ' + t('checkStock.cannotDele'));
		}
	}
	useMessageBox()
		.confirm(t(`operation.permanentDeletion`))
		.then(async () => {
			await DeleteCheckStockDetail({ "list": selectedAry }).then(
				(res) => {
					getDataList();
					useMessage().success('删除成功');
				},
				(error) => {
					useMessage().error(error?.msg || '删除失败');
				}
			);
		});
}
//原材料、半成品标签通用打印
const print = () => {
  var selectedAry = tableRef.value.getSelectionRows();
  if (!PrinterName.value) {
    ElMessage.error(t('bar.selectPrinter'));
    return;
  }
  if (selectedAry.length == 0) {
    ElMessage.error(t('bar.selectBarcodes'));
    return;
  }
  selectedAry.forEach(element => {
    barcodePrint({
      "barcode": element.barcode,
      "printerName": PrinterName.value,
      "operatePage": "CheckStockHistory"
    }).then((res) => {

    });
  });

}
</script>